package my.jwds.p661;

import com.alibaba.fastjson.JSONObject;

import java.util.Arrays;

public class ImageSmoother {

    public static void main(String[] args) {

        ImageSmoother obj = new ImageSmoother();
        int [][] img = JSONObject.parseObject("[[100,200,100]]",int[][].class);
        long start = System.currentTimeMillis();
        int [][] res = obj.imageSmoother(img);
        for (int[] ints : res) {
            System.out.println(Arrays.toString(ints));
        }
        System.out.println("运行时间:" + (System.currentTimeMillis() - start));
    }

    public int[][] imageSmoother(int[][] img) {
        int m = img.length,n = img[0].length;
        if (m == 1 && n == 1)return img;

        int[][]res = new int[m][n];


        if (m > 1 && n == 1){

            res[0][0] = (img[0][0] + img[1][0])/2;
            res[m-1][0] = (img[m-1][0] + img[m-2][0])/2;

            for (int i = 1; i < m-1; i++) {
                res[i][0] = (img[i-1][0] + img[i][0]+ img[i+1][0])/3;
            }
            return res;
        }else if (m == 1 && n > 1){
            res[0][0] = (img[0][0] + img[0][1])/2;
            res[0][n-1] = (img[0][n-1] + img[0][n-2])/2;

            for (int i = 1; i < n-1; i++) {
                res[0][i] = (img[0][i-1] + img[0][i]+ img[0][i+1])/3;
            }
            return res;
        }


        res[0][0] = (img[0][0] + img[0][1] + img[1][0] + img[1][1])/4;
        res[0][n-1] = (img[0][n-1] + img[0][n-2] + img[1][n-1] + img[1][n-2])/4;
        res[m-1][0] = (img[m-1][0] + img[m-1][1] + img[m-2][0] + img[m-2][1])/4;
        res[m-1][n-1] = (img[m-1][n-1] + img[m-1][n-2] + img[m-2][n-1] + img[m-2][n-2])/4;

        for (int i = 1; i < n-1; i++) {
            res[0][i] = (img[0][i-1] + img[0][i] + img[0][i+1] + img[1][i-1] + img[1][i] + img[1][i+1])/6;
            res[m-1][i] = (img[m-1][i-1] + img[m-1][i] + img[m-1][i+1] + img[m-2][i-1] + img[m-2][i] + img[m-2][i+1])/6;
        }
        for (int i = 1; i < m-1; i++) {
            res[i][0] = (img[i-1][0] + img[i][0] + img[i+1][0] + img[i-1][1] + img[i][1] + img[i+1][1])/6;
            res[i][n-1] = (img[i-1][n-1] + img[i][n-1] + img[i+1][n-1] + img[i-1][n-2] + img[i][n-2] + img[i+1][n-2])/6;
        }

        for (int i = 1; i < m-1; i++) {
            for (int j = 1; j < n-1; j++) {
                res[i][j] = (img[i-1][j-1] + img[i-1][j]  + img[i-1][j+1] + img[i][j-1] + img[i][j]  + img[i][j+1] + img[i+1][j-1] + img[i+1][j]  + img[i+1][j+1])/9;
            }
        }

        return res;
    }
}